package controllers

import (
	"encoding/json"
	// "errors"
	// "strconv"
	// "strings"
	// "ga_wz_backend/libs/encrypt"
	"gitee.com/lzqysoft/ga_wz_backend/models"

	"github.com/astaxie/beego"
)

// SalesController operations for Sales
type SalesController struct {
	CommonController
}

// URLMapping ...
func (c *SalesController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
}

// Post ...
// @Title Post
// @Description create Sales
// @Param	body		body 	models.Sales	true		"body for Sales content"
// @Success 201 {int} models.Sales
// @Failure 403 body is empty
// @router / [post]
func (c *SalesController) Post() {
	var v models.Sales
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &v); err == nil {
		if _, err := models.AddSales(&v); err == nil {
			c.Ctx.Output.SetStatus(201)
			c.Data["json"] = v
		} else {
			c.Data["json"] = err.Error()
		}
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// GetOne ...
// @Title Get One
// @Description get Sales by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Sales
// @Failure 403 :id is empty
// @router /:id [get]
func (c *SalesController) GetOne() {
	id := c.Ctx.Input.Param(":id")
	// id, _ := strconv.Atoi(idStr)
	v, err := models.GetSalesById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Sales
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Sales
// @Failure 403
// @router /GetAll/:id
func (c *SalesController) GetAll() {
	id := c.Ctx.Input.Param(":id")
	beego.Debug(id)
	sales, err := models.GetSalesByOrder(id)
	receiv, err := models.GetReceivByOrderId(id)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrNoData)
	}
	td := make(map[string]interface{})
	td["sales"] = sales
	td["receiv"] = receiv
	c.RetSuccess(td)
}
